#!/bin/sh
# tlp - handle added usb devices
#
# Copyright (c) 2025 Thomas Koch <linrunner at gmx.net> and others.
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Remark: the calling udev rule is triggered for "base" devices only,
#         not for the corresponding subdevices.

# --- Source libraries

for lib in @TLP_TLIB@/tlp-func-base @TLP_FLIB@/15-tlp-func-disk @TLP_FLIB@/20-tlp-func-usb; do
    # shellcheck disable=SC1090
    . "$lib" || exit 70
done

# --- MAIN
# shellcheck disable=SC2034
_bgtask=1

# read configuration: quit on error, trace allowed
read_config 0

# quit if TLP disabled
check_tlp_enabled || do_exit 0

if [ "$X_USB_ENV_TRACE" = "1" ]; then
    echo_debug "usb" "tlp_usb_udev.env = $(printenv)"
fi

case "$1" in
    usb) # usb devices in general
        [ "$USB_AUTOSUSPEND" = "1" ] || do_exit 0
        # quit if usb autosuspend disabled

        # USB autosuspend has two principal operation modes:
        #
        # Mode 1 (optional):
        # - System startup is handled by tlp-functions:set_usb_suspend()
        # - Startup completion is signaled by "flag file" $USB_DONE
        # - Newly added devices are handled by this udev script
        # - Mode 1 is enabled by the private config variable X_TLP_USB_MODE=1
        #
        # Mode 2 (default):
        # - Everything - including system startup, but not shutdown - is handled by this udev script

        # quit if mode 1 and no startup completion flag
        [ "$X_TLP_USB_MODE" = "1" ] && ! check_run_flag "$USB_DONE" && do_exit 0

        # handle device
        usb_suspend_device "/sys$2" "udev"
        ;;

    disk) # (s)ata disks attached via usb
        echo_debug "usb" "tlp_usb_udev.disk: bus=$ID_BUS dev=/sys$2 "

        get_next_power_profile usb-udev-disk
        dev="${2##*/block/}"
        # shellcheck disable=SC2154
        set_ahci_disk_runtime_pm "$_pp_next" "$dev"
        set_disk_apm_level "$_pp_next" "$dev"
        set_disk_spindown_timeout "$_pp_next" "$dev"
        set_disk_iosched "$dev"
        ;;
esac

do_exit 0
